import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/dateline_event.dart';
import '../providers/dateline_providers.dart';

/// 时间线事件类型过滤器提供者
final datelineTypeFilterProvider = StateProvider<DatelineEventType?>((ref) => null);

/// 时间线事件类型过滤器组件
class DatelineTypeFilter extends ConsumerWidget {
  /// 构造函数
  const DatelineTypeFilter({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 获取当前选中的时间线事件类型
    final selectedEventType = ref.watch(datelineTypeFilterProvider);
    
    // 从后台加载事件类型列表
    final typesAsync = ref.watch(datelineTypesProvider);

    return Container(
      height: 60,
      margin: const EdgeInsets.symmetric(vertical: 8),
      child: typesAsync.when(
        data: (types) {
          return ListView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            children: [
              // 全部事件选项
              _buildFilterChip(
                context,
                ref,
                null,
                '全部',
                Icons.event,
                Colors.blue,
                selectedEventType == null,
              ),
              // 为从后台加载的事件类型创建过滤器选项
              for (final eventType in types)
                _buildFilterChip(
                  context,
                  ref,
                  eventType,
                  eventType.displayName,
                  eventType.icon.icon!,
                  eventType.color,
                  selectedEventType == eventType,
                ),
            ],
          );
        },
        loading: () {
          return ListView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            children: [
              // 加载中显示骨架屏
              _buildSkeletonChip(),
              _buildSkeletonChip(),
              _buildSkeletonChip(),
            ],
          );
        },
        error: (error, stack) {
          print('加载日历类型失败: $error');
          return ListView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            children: [
              // 错误时显示全部选项
              _buildFilterChip(
                context,
                ref,
                null,
                '全部',
                Icons.event,
                Colors.blue,
                selectedEventType == null,
              ),
            ],
          );
        },
      ),
    );
  }
  
  /// 构建骨架屏芯片（加载中）
  Widget _buildSkeletonChip() {
    return Padding(
      padding: const EdgeInsets.only(right: 8),
      child: Container(
        width: 80,
        height: 32,
        decoration: BoxDecoration(
          color: Colors.grey.shade300,
          borderRadius: BorderRadius.circular(16),
        ),
      ),
    );
  }

  /// 构建过滤器芯片
  Widget _buildFilterChip(
    BuildContext context,
    WidgetRef ref,
    DatelineEventType? eventType,
    String label,
    IconData icon,
    Color color,
    bool isSelected,
  ) {
    return Padding(
      padding: const EdgeInsets.only(right: 8),
      child: FilterChip(
        selected: isSelected,
        label: Text(label),
        avatar: Icon(
          icon,
          color: isSelected ? Colors.white : color,
          size: 18,
        ),
        backgroundColor: Colors.grey.shade200,
        selectedColor: color,
        labelStyle: TextStyle(
          color: isSelected ? Colors.white : Colors.black87,
          fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
        ),
        onSelected: (selected) {
          // 更新选中的事件类型
          ref.read(datelineTypeFilterProvider.notifier).state = selected ? eventType : null;
          
          // 调用接口获取对应类型的数据
          if (selected) {
            if (eventType != null) {
              // 触发从接口加载指定类型的数据
              ref.invalidate(datelineEventsByTypeProvider(eventType));
            } else {
              // 加载所有数据
              ref.invalidate(datelineEventsByTypeProvider(null));
            }
          }
        },
      ),
    );
  }
}
